import { defineStore } from "pinia";
import { removeToken, removeRefreshToken } from "@/utils/auth";

export const useUserStore = defineStore("user", {
  state: () => ({
    userInfo: localStorage.getItem("userInfo") ? JSON.parse(localStorage.getItem("userInfo")) : {},
    permissions: localStorage.getItem("permissions") ? JSON.parse(localStorage.getItem("permissions")) : [],
    isUpdated: false,
  }),

  getters: {
    isLoggedIn: () => !!localStorage.getItem("token"),
    getUserInfo: (state) => state.userInfo,
    getPermissions: (state) => state.permissions,
    isUpdatedUserInfo: (state) => state.isUpdated,
  },

  actions: {
    setUserInfo(info) {
      this.userInfo = info;
      localStorage.setItem("userInfo", JSON.stringify(info));
    },
    setPermissions(permissions) {
      this.permissions = permissions;
      localStorage.setItem("permissions", JSON.stringify(permissions));
    },
    setIsUpdated(isUpdated) {
      this.isUpdated = isUpdated;
    },
    clearPermissions() {
      this.permissions = [];
    },
    logout() {
      this.userInfo = null;
      this.permissions = [];
      // 从localStorage中移除token，但不在store中存储token
      removeToken();
      removeRefreshToken();
    },
  },
});
